<template>
  <div>
    <el-button type="primary" @click="addUser()">新增</el-button>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="id" width="100"></el-table-column>
      <el-table-column prop="name" label="姓名" width="150"></el-table-column>
     <el-table-column prop="userface" label="头像" width="150">
       <template   slot-scope="scope">            
                    <img :src="scope.row.userface"  min-width="70" height="70" />
                 </template>         
     </el-table-column>

      <el-table-column prop="username" label="用户名" width="175"></el-table-column>
      <el-table-column prop="phone" label="手机号" width="200"></el-table-column>
      <el-table-column prop="telephone" label="住宅电话" width="200"></el-table-column>
      <el-table-column prop="roleListStr" label="角色列表" width="200"></el-table-column>
      <el-table-column prop="province" label="省" width="200" v-if="false"></el-table-column>
      <el-table-column prop="city" label="市" width="200" v-if="false"></el-table-column>
      <el-table-column prop="district" label="区" width="200" v-if="false"></el-table-column>

      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" type="text" size="small">编辑</el-button>
          <el-button @click="shouquan(scope.row)" type="text" size="small">授权</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!--新增编辑用户开始-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="form.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="省市区" :label-width="formLabelWidth" prop="value">
          <el-cascader v-model="form.value" :options="options" @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="上传头像" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            ref="upload1"
            action=""
            :auto-upload="false"
            :limit="1 "
            multiple
            accept="application/jpg"
            :file-list="fileList"
            list-type="picture"
            :on-change="handlerChange"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleUser()">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateUser('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!--新增编辑用户结束-->

    <el-dialog title="授权" :visible.sync="dialogShouquan">
      <el-checkbox
        :indeterminate="isIndeterminate"
        v-model="checkAll"
        @change="handleCheckAllChange"
      >全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
        <!-- <el-checkbox v-for="role in roles" :label="city" :key="">{{role.name}}</el-checkbox> -->
        <el-checkbox v-for="role in roles" :label="role.id" :key="role.id">{{role.nameZh}}</el-checkbox>
      </el-checkbox-group>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShouquan = false">取 消</el-button>
        <el-button type="primary" @click="submitUserRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "app",

  methods: {
    handlerChange(file,files){
      console.log(file,files);
      this.fileList = files;
    },
    submitUserRole() {
      //2、授权保存
      var $this = this;
      this.axios({
        method: "put",
        url: this.requestUrl + "/role",
        data: { uid: this.uid, roleList: this.checkedCities }
      }).then(function(res) {
        console.log("修改角色列表.....", res);
        $this.$message({
          message: res.data.msg,
          type: "success"
        });
      });
    },
    shouquan(row) {
      this.checkedCities = [];
      this.uid = row.id;
      //1、弹出层
      this.dialogShouquan = true;
      var $this = this;
      //2、查询所有的角色以复选框进行显示
      this.axios({
        method: "get",
        url: this.requestUrl + "/role/all"
      }).then(function(res) {
        console.log("查询所有角色列表.....", res);
        $this.roles = res.data.obj;
      });

      //3、回显 根据选择的用户对应角色进行回显

      var $this = this;
      //2、查询所有的角色以复选框进行显示
      this.axios({
        method: "get",
        url: this.requestUrl + "/role/getRoleListByUid",
        params: { uid: this.uid }
      }).then(function(res) {
        console.log("查询所有角色列表.....", res);
        var list = res.data.obj;
        for (var i = 0; i < list.length; i++) {
          $this.checkedCities.push(list[i].rid);
        }
      });
    },
    handleCheckAllChange(val) {
      console.log("val{}", val);
      this.checkedCities = [];
      if (val) {
        for (var i = 0; i < this.roles.length; i++) {
          this.checkedCities.push(this.roles[i].id);
        }
      }
      console.log("全选this.checkedCities：", this.checkedCities);
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      console.log("value{}", value);
      console.log("选中this.checkedCities:{}", this.checkedCities);
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.roles.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.roles.length;
    },

    getUser() {
      var $this = this;
      this.axios({
        method: "get",
        url: this.requestUrl + "/user/userList",
        params: { pageNo: this.currentPage4, pageSize: this.pageSize }
      }).then(function(res) {
        console.log(res);
        $this.tableData = res.data.obj.list;
        $this.total = res.data.obj.total;
      });
    },

    //编辑用户
    handleClick(row) {
      this.userClear();
      console.log(row);
      this.title = "编辑用户";
      this.dialogFormVisible = true;
      this.userMethod = "put";

      this.form.name = row.name;
      this.form.username = row.username;
      this.form['id'] = row.id;
      this.fileList = [{name:'1.jpg',url:row.userface}];
      this.imUrlList.push(row.userface);
      this.form.value= [row.province,row.city,row.district];
      // console.log('------------>',this.$refs.upload1.getFile());
      // return;
      // var file = this.$refs.upload.files[0];
      // var imgURL = window.URL.createObjectURL(file); 
      // var a = new FileReader();
      // a.readAsDataURL(file);
      this.form.id = row.id;
    },
    //新增用户
    addUser() {
      this.userClear();
      this.dialogFormVisible = true;
      this.title = "新增用户";
      this.userMethod = "post";
    },
    //编辑或者新增提交到后台
    addOrUpdateUser(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {

          var formData = new FormData();
          //将原来form 的值添加到 formData中
          for(var o in this.form){
            formData.append(o,this.form[o]);
          }
          this.imUrlList.forEach(function(url){
            formData.append('images',url);
          })
          this.fileList.forEach(function(file){
              if(file.raw){
                formData.append('files',file.raw,file.name);
              }
          });
            //设置图片上传的格式
          let config = {
            "Content-Type": "multipart/form-data"
          };

          console.log("formData----------------->",formData);
          for(var key of formData.keys()){
               console.log("key:{},value:{}",key,formData.get(key));
          }
          var $this = this;
          this.axios({
            method: this.userMethod,
            url: this.requestUrl + this.userUrl,
            data: formData,
            config:config
          }).then(function(res) {
            console.log("编辑或者新增返回:{}", res);
            $this.$message({
              message: res.data.msg,
              type: "success"
            });
            if (res.data.code == 200) {
              $this.dialogFormVisible = false;
              $this.getUser();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //编辑新增用户弹出层取消按钮
    dialogFormVisibleUser() {
      this.dialogFormVisible = false;
      this.userClear();
    },
    //清空弹出层的form表单的内容
    userClear() {
      for (var item in this.form) {
        if (Array.isArray(this.form[item])) {
          this.form[item] = [];
        } else {
          this.form[item] = null;
        }
      }
    },
    // 级联选择器的改变事件
    handleChange(value) {
      console.log(value);
    },
    //加载省市区三级联动内容
    loadnation() {
      var $this = this;
      this.axios({
        method: "get",
        url: this.requestUrl + "/nation/list"
      }).then(function(res) {
        console.log("加载省市区{}", res);
        $this.options = res.data.obj;
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getUser();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage4 = val;
      this.getUser();
    }
  },
  data() {
    return {
      dialogShouquan: false,
      checkAll: false,
      checkedCities: [],
      roles: [],
      uid: "",
      isIndeterminate: true,
      msg: "Welcome to Your Vue.js App",
      list: [],
      tableData: [],
      currentPage4: 1,
      pageSizes: [1, 2, 3, 4],
      pageSize: 2,
      total: 400,
      dialogFormVisible: false,
      form: {
        name: "",
        username: "",
        value: []
      },
      formLabelWidth: "120px",
      title: "",
      userMethod: "",
      userUrl: "/user",
      options: [],
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10个字符", trigger: "blur" }
        ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10个字符", trigger: "blur" }
        ],
        value: [{ required: true, message: "请选择省市区", trigger: "blur" }]
      },
      fileList:[],
      imageUrl:'',
      imUrlList:[],
    };
  },
  mounted() {
    this.getUser();
    this.loadnation();
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>